<template>
  <div class="register" v-if="registerBkImgs.length">
    <transition-group name="fade" tag="ul" class="register-carousel">
      <li
        class="register-carousel__item"
        v-for="item in registerBkImgs"
        :key="item.id"
        v-show="id === item.id"
      >
        <img class="register-carousel__img" :src="item.url" alt="图片加载失败" /></li
    ></transition-group>
    <div class="register-title">
      <span>欢迎来到TYChat</span><br />
      <span>快乐沟通每一天</span>
    </div>
    <div class="register-container">
      <p class="register-container__title">注册</p>
      <register-form :is-request="isRequest"></register-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onBeforeMount, onBeforeUnmount } from "@vue/runtime-core";
import LoadingBar from "@/plugins/loadingBar";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import registerForm from "./registerForm.vue";
import { usePinia } from "@/pinia/index";
import { storeToRefs } from "pinia";

const router = useRouter();
const indexStore = usePinia();
const { codeUrl, registerBkImgs } = storeToRefs(indexStore);

/**
 * 该组件的根元素的高度
 */
let winHei = ref<string>("");

/**
 * 浏览器的可视高度改变则组件的根元素的高度也随之改变
 */
const handleToWid: () => void = (): void => {
  // 获取浏览器的可视高度
  const hei: number =
    globalThis.innerHeight ||
    document.body.clientHeight ||
    document.documentElement.clientHeight;
  if (hei <= 500) winHei.value = "500px";
  else winHei.value = `${hei}px`;
};
// 给浏览器添加监听窗口大小变化的事件
window.addEventListener("resize", handleToWid);

/**
 * 当前显示背景图片的id值
 */
const id = ref<number>(1);
/**
 * 存储了setInterval函数，便于清除
 */
const timing = ref<number>(0);
// 开始轮播
const startCarousel = () => {
  timing.value = window.setInterval(() => {
    id.value++;
    if (id.value === 6) id.value = 1;
  }, 8000);
};

/**
 * 根据用户进入还是离开页面的状态来判断是否停止轮播
 */
const isCarousel: () => void = (): void => {
  const status: string = document.visibilityState; // 获取用户的状态 (离开页面还是进入页面)
  switch (status) {
    case "visible":
      // 当用户进入页面时开始轮播
      startCarousel();
      break;
    case "hidden":
      clearInterval(timing.value);
      break;
    default:
      clearInterval(timing.value);
  }
};

/**
 * 是否正在请求背景图片
 */
const isRequest = ref<boolean>(false);

onBeforeMount(() => {
  // 初始化组件根元素的高度
  handleToWid();
  // 添加该事件用来判断用户是否进入离开页面
  document.addEventListener("visibilitychange", isCarousel);
  if (registerBkImgs.value.length && codeUrl.value.length) startCarousel();
  // 同时请求背景图片和验证码
  else if (!registerBkImgs.value.length && !codeUrl.value.length) {
    isRequest.value = true;
    // 加载条类
    const loBar: LoadingBar = new LoadingBar();
    loBar.start();
    Promise.all([
      // 请求验证码
      indexStore.getVerCode(),
      // 请求注册页面的背景图片
      indexStore.getRegisterBkImgs(),
    ])
      .then((codes: number[]) => {
        isRequest.value = false;
        if (!codes.includes(0)) {
          loBar.finsh();
          startCarousel();
        } else {
          loBar.unMount();
          router.push("/404");
        }
      })
      .catch(() => {
        isRequest.value = false;
        loBar.unMount();
        router.push("/404");
      });
  } else {
    isRequest.value = true;
    // 加载条类
    const loBar: LoadingBar = new LoadingBar();
    loBar.start();
    // 请求背景图片
    if (!registerBkImgs.value.length) {
      indexStore
        .getRegisterBkImgs()
        .then((code: number) => {
          isRequest.value = false;
          if (code === 1) {
            loBar.finsh();
            startCarousel();
          } else {
            loBar.unMount();
            ElMessage.error({
              message: "请求图片失败",
            });
          }
        })
        .catch(() => {
          isRequest.value = false;
          loBar.unMount();
          router.push("/404");
        });
    }
    // 请求验证码
    else if (!codeUrl.value.length) {
      indexStore
        .getVerCode()
        .then((code: number) => {
          isRequest.value = false;
          if (code === 1) {
            loBar.finsh();
            startCarousel();
          } else {
            loBar.unMount();
            router.push("/404");
          }
        })
        .catch(() => {
          isRequest.value = false;
          loBar.unMount();
          router.push("/404");
        });
    }
  }
});

// 组件卸载前移除该事件
onBeforeUnmount(() => {
  window.removeEventListener("resize", handleToWid);
  clearInterval(timing.value);
});
</script>
<style lang="scss" scoped>
.fade {
  @include fade(1.5s, ease);
}
.register {
  height: v-bind(winHei);
  min-width: 900px;
  overflow: hidden;
  position: relative;

  &-carousel {
    @include setWidHei(100%, 100%);

    &__item {
      @include setWidHei(100%, 100%);
      position: absolute;
      top: 0;
      left: 0;
    }

    &__img {
      @include setWidHei(100%, 100%);
      object-fit: cover;
    }
  }

  &-title {
    position: absolute;
    top: 5%;
    left: 5%;
    color: #fff;

    span {
      &:first-child {
        font: {
          size: 2rem;
          weight: bold;
          family: FZShuTi, STHupo, STCaiyun;
        }
      }

      &:last-child {
        display: inline-block;
        margin: 10px;
        letter-spacing: 1px;
        font: 1.7rem STXingkai;
      }
    }
  }

  &-container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    @include card(450px, 400px, 5px);

    &__title {
      margin: 0;
      text-align: center;
      font-size: 20px;
    }
  }
}
</style>
